﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Epic.HandyExtensions;
using System.Resources;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;

namespace Epic.Core
{
    public static class FlagTypeHelper<T>
        where T : struct, IComparable, IFormattable, IConvertible
    {
        #region Static

        private static Func<T, T, bool> smHasDelegate;


        static FlagTypeHelper()
        {
            if (!typeof(T).IsFlagType())
                throw new ArgumentOutOfRangeException("T");

            InitializeHasDelegate();
        }

        private static void InitializeHasDelegate()
        {
            var dm = new DynamicMethod("Has", typeof(bool), new[] { typeof(T), typeof(T) });
            var il = dm.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.And);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ceq);
            il.Emit(OpCodes.Ret);
            smHasDelegate = (Func<T, T, bool>)dm.CreateDelegate(typeof(Func<T, T, bool>));
        }

        public static bool Has(T value, T flag)
        {
            return smHasDelegate(value, flag);
        }

        #endregion

        //#region Instance

        //public string KeyFormat { get; private set; }
        //public ResourceManager ResourceManager { get; set; }
        //public CultureInfo Culture { get; set; }

        //public FlagTypeHelper(string keyFormat)
        //{
        //    KeyFormat = keyFormat;
        //}

        //#endregion

    }
}
